﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Mang24k99.Model.COMM;
using System.IO;
using System.Drawing;
using Mang24k99.Business.COMM;

namespace Mang24k99.Web.OrgList
{
    public partial class GoldCorpAdd : System.Web.UI.Page
    {
        //从数据库系统参数设置表中读取logo图片的高度、宽度、大小设置
        //1-高度设置，2-宽度设置，3-大小设置
        protected string strWidth = BKtCommBaseInfo.GetValue("2");
        protected string strHeight = BKtCommBaseInfo.GetValue("1");
        protected string strSize = BKtCommBaseInfo.GetValue("3");
        protected void Page_Load(object sender, EventArgs e)
        {
            //TODO:asdfasdf
            //this.FileUpload1.
            this.lbSize.Text="logo预览"+strWidth+"*"+strHeight;
            if (!IsPostBack)
            {
                SetImgSize();
                Bindate();
            }
        }
        //设置logo图片显示大小
        private void SetImgSize()
        {
            //默认值
            this.imgLog.Width =Unit.Pixel(120);
            this.imgLog.Height = Unit.Pixel(35);
            
			if (strWidth!=null && Common.PageValidate.IsNumber(strWidth)==true)
			{
				this.imgLog.Width = Unit.Pixel(Convert.ToInt32(strWidth));
			}
           
            if (strHeight != null && Common.PageValidate.IsNumber(strHeight)==true)
            {
                this.imgLog.Height = Unit.Pixel(Convert.ToInt32(strHeight));
            }
            
        }

        /// <summary>
        /// 新增修改保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {

            if (this.btnSave.Text == "新增")
            {
                if (PageValidate() == false)
                {
                    return;
                }
                byte[] bytearray = GetByteArray();
                if (bytearray == null)
                {
                    string strMsg = "必须上传Logo！";
                    Common.MessageBox.Show(this.Page, strMsg);
                    return;
                }
                MKtCommOrglist orglist = new MKtCommOrglist();
                MKtCommOrglist parent = BKtCommOrglist.Find(2);
                orglist.OrgnizeNO = (int)BKtCommOrglist.GetMaxNum() + 1;
                orglist.OrgnizeName = this.txtOrgName.Text.Trim();
                orglist.ParentNO = 2;
                orglist.CompsiteNO = parent.CompsiteNO + "," + orglist.OrgnizeNO;
                orglist.IsValidate = 1;
                orglist.IsColumn = 1;
				orglist.IsGrant = Convert.ToInt32(rbtnListGrant.SelectedValue);
                orglist.OrangeLayer = 2;
                orglist.LOGO = bytearray;
				if (Session["ImgName"] != null)
				{
					orglist.LogoPath = Session["ImgName"].ToString();
				}
                string where = "orglist.ParentNO=2 ";
                int order = BKtCommOrglist.SelectMaxOrder(where);
                orglist.LevelOrder = order + 1;
                orglist.InputTime = DateTime.Now;

                try
                {
                    BKtCommOrglist.Create(orglist);
                    string strMsg = "新增机构成功！";
                    Common.MessageBox.Show(this.Page, strMsg);
                    Bindate();
                }
                catch (System.Exception ex)
                {
                    throw;
                }
            }
            if (this.btnSave.Text == "更新")
            {
                if (this.txtOrgName.Text.Trim() != Session["orgname"].ToString())
                {
                    if (PageValidate() == false)
                    {
                        return;
                    }
                }
                byte[] bytearray = GetByteArray();
                if (bytearray == null)
                {
                    string strMsg = "必须上传logo！";
                    Common.MessageBox.Show(this.Page, strMsg);
                    return;
                }
                int orgno = Int32.Parse(this.txtOrgNO.Text);
                MKtCommOrglist orglist = (MKtCommOrglist)BKtCommOrglist.Find(orgno);
                orglist.OrgnizeName = this.txtOrgName.Text.Trim();
                orglist.LOGO = bytearray;
				orglist.IsGrant = Convert.ToInt32(rbtnListGrant.SelectedValue);
                orglist.ModifyTime = DateTime.Now;
				if (Session["ImgName"]!=null)
				{
					orglist.LogoPath = Session["ImgName"].ToString();
				}
				
                try
                {
                    BKtCommOrglist.Update(orglist);
                    string strMsg = "更新成功！";
                    Common.MessageBox.Show(this.Page, strMsg);
                    Bindate();
                }
                catch (System.Exception ex)
                {
                    throw;
                }
            }
            PageClear();
        }
        /// <summary>
        /// 页面有效性验证
        /// </summary>
        /// <returns></returns>
        public bool PageValidate()
        {
            if (this.txtOrgName.Text.Trim() == "")
            {
                string strMsg = "金商机构名称不能为空！";
                Common.MessageBox.Show(this.Page, strMsg);
                return false;
            }
            else
            {
                string where = "orglist.ParentNO=2 and orglist.OrgnizeName='" + this.txtOrgName.Text.Trim() + "'";
                MKtCommOrglist[] list = (MKtCommOrglist[])BKtCommOrglist.SelectByWhere(where);
                if (list.Length != 0)
                {
                    string strMsg = "金商机构名称不能重复！";
                    Common.MessageBox.Show(this.Page, strMsg);
                    return false;
                }
            }

            return true;
        }
        /// <summary>
        /// 返回图片byte数组
        /// </summary>
        /// <returns></returns>
        public byte[] GetByteArray()
        {
            if (Session["bytearray"] != null)
            {
                byte[] bytearray = (byte[])Session["bytearray"];
                Session["bytearray"] = null;
                return bytearray;
            }
            else if (Session["logo"] != null)
            {
                byte[] bytearray = (byte[])Session["logo"];
                Session["logo"] = null;
                return bytearray;
            }
            return null;
        }
        /// <summary>
        /// 预览并显示图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string filetype = this.FileUpload1.PostedFile.ContentType;
                int fileLength = this.FileUpload1.PostedFile.ContentLength;
				Single maxSize = 1.5f;
                if (filetype != "image/pjpeg" && filetype!="image/jpeg")
                {
                    string strMsg = "图片格式不对，请上传.jpg格式图片！";
                    Common.MessageBox.Show(this.Page, strMsg);
                    return ;
                }
                
                if (strSize!=null && Common.PageValidate.IsFloat(strSize))
                {
					maxSize = Convert.ToSingle(strSize);
                }
				if ((float)fileLength / 1024 > maxSize)
                {
					string strMsg = "图片大小不能大于" + maxSize + "K！";
                    Common.MessageBox.Show(this.Page, strMsg);
                    return ;
                }
				System.Drawing.Image upImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
				if (upImage.Width.ToString() != strWidth || upImage.Height.ToString() != strHeight)
				{
					string strMsg = "图片的规格必须为" + strWidth + "×" + strHeight;
					Common.MessageBox.Show(this.Page, strMsg);
					return;
				}

				string fname = this.FileUpload1.FileName;       ///得到文件名
                string savePath = Server.MapPath("LogImage") + "\\" + fname;
				byte[] ByteArray = FileUpload1.FileBytes;
				try
				{
					//上传到服务器目录
					Common.FileHelper.SaveFile(savePath,FileUpload1.FileBytes);
					this.imgLog.ImageUrl = "LogImage/" + fname;           //图片显示
				}
				catch (System.Exception ex)
				{
					throw(ex);
				}
                Session["bytearray"] = ByteArray;
				Session["ImgName"] = fname;
            }
        }
        /// <summary>
        /// 绑定gridview
        /// </summary>
        public void Bindate()
        {
            string where = "orglist.ParentNO=2 order by orglist.LevelOrder";
            MKtCommOrglist[] orglist = (MKtCommOrglist[])BKtCommOrglist.SelectByWhere(where);
            this.grdList.DataSource = orglist;
            this.grdList.DataBind();
        }
        /// <summary>
        /// 选择gridview中某一行进行编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = this.grdList.SelectedIndex;
            string orgno = this.grdList.Rows[index].Cells[1].Text;
            MKtCommOrglist orglist = BKtCommOrglist.Find(Int32.Parse(orgno));
            this.txtOrgName.Text = orglist.OrgnizeName;
            this.txtOrgNO.Text = orglist.OrgnizeNO.ToString();
            Session["orgname"] = orglist.OrgnizeName;
            this.btnSave.Text = "更新";
			rbtnListGrant.SelectedValue = orglist.IsGrant.ToString();
            imgLog.ImageUrl = "ShowPicture.aspx?PicId=" + orglist.OrgnizeNO;
            Session["logo"] = orglist.LOGO;
			Session["ImgName"]=orglist.LogoPath;
        }

        /// <summary>
        /// 删除操作(逻辑删除)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void grdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            MKtCommOrglist orglist = new MKtCommOrglist();
            int id = Int32.Parse(this.grdList.Rows[e.RowIndex].Cells[1].Text);
            orglist = BKtCommOrglist.Find(id);
            bool result = BKtCommOrglist.Delete(orglist);
            if (result == true)
            {
                string strMsg = "删除成功！";
                Common.MessageBox.Show(this.Page, strMsg);
                Bindate();
                PageClear();
            }
            else
            {
                string strMsg = "删除失败！";
                Common.MessageBox.Show(this.Page, strMsg);

            }
        }
        /// <summary>
        /// 点击取消清空页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            PageClear();
        }
        /// <summary>
        /// 清空页面
        /// </summary>
        public void PageClear()
        {
            this.btnSave.Text = "新增";
            this.txtOrgName.Text = "";
            this.txtOrgNO.Text = "";
            this.txtOrgNO.ReadOnly = false;
            Session["logo"] = null;
            Session["bytearray"] = null;
            Session["orgname"] = null;
			Session["ImgName"] = null;
            this.imgLog.ImageUrl = "~/OrgList/LogImage/NoImage.jpg";
        }

        public string GetStatus(int status)
        {
            if (status == 1)
            {
                return "显示";
            }
            else
            {
                return "隐藏";
            }
        }
        /// <summary>
        /// 隐藏机构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName=="hidden")
            {
                MKtCommOrglist orglist = new MKtCommOrglist();
                int NO = Int32.Parse(e.CommandArgument.ToString());
                orglist = BKtCommOrglist.Find(NO);
                if (orglist.IsColumn==1)
                {
                    orglist.IsColumn = 0;
                }
                else
                {
                    orglist.IsColumn=1;
                }
                BKtCommOrglist.Update(orglist);
                Bindate();
            }
        }
    }
}
